package View;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.wonyesoft.wuliu.R;

import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.TimePicker.OnTimeChangedListener;

/**
 * @author 作者陈修园 E-mail:
 * @date 创建时间：2015-6-23 上午11:27:03
 * @version 1.0
 * @parameter 日期选择器
 * @since
 * @return
 */
public class DatePickerFragment implements OnDateChangedListener,
		OnTimeChangedListener {

	private Context context;
	/**
	 * 默认时间
	 */
	private String initDateTime;

	/**
	 * 选择的时间
	 */
	private String dateTime;

	private TimePicker timePicker;
	private DatePicker datePicker;

	/**
	 * 
	 * @param context
	 * @param 弹出对话框
	 */
	private Dialog alertdialog;

	/**
	 * 是否需要 选择时间
	 */
	private boolean flag = true;

	/**
	 * 日期选择的回调接口
	 */
	private onChoseData callback;

	/**
	 * 用户选择的日期
	 */
	private String userChoseData;

	/**
	 * setNeedTomorrow 必须是明天以前
	 */
	private boolean needTomorrow = false;
	private boolean timeRight = true;

	/**
	 * 时间选择器的title
	 */
	private String titleString;
	
	/**
	 * 放弃的对话框
	 */
	private String giveupString;
	
	public DatePickerFragment(Context context, String initDataTime, boolean flag,String title,String giveupString) {
		this.context = context;
		this.initDateTime = initDataTime;
		this.flag = flag;
		this.titleString=title;
		this.giveupString=giveupString;
	}

	public void init(DatePicker datePicker, TimePicker timePicker) {
		Calendar calendar = Calendar.getInstance();
		if ((null != initDateTime) || "".equals(initDateTime)) {
			calendar = this.getCalendarByInintData(initDateTime);
		} else {
			initDateTime = calendar.get(Calendar.YEAR) + "年"
					+ calendar.get(Calendar.MONTH) + "月"
					+ calendar.get(Calendar.DAY_OF_MONTH) + "日 "
					+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
					+ calendar.get(Calendar.MINUTE);
		}

		datePicker.init(calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), this);
		Log.v("获得的时间", "" + calendar.get(Calendar.HOUR_OF_DAY));

		// timePicker.setcur
		timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
		timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));

	}

	/**
	 * 
	 * @param needTomorrow
	 *            设置是否必须是今天以前
	 */
	public void setNeedTomorrow(boolean needTomorrow) {
		this.needTomorrow = needTomorrow;
	}

	/**
	 * 弹出日期时间选择框方法
	 * 
	 * @param inputDate
	 *            :为需要设置的日期时间文本编辑框
	 * @return
	 */
	public Dialog dateTimePicKDialog(final TextView inputDate) {
		LinearLayout dateTimeLayout = (LinearLayout) ((Activity) context)
				.getLayoutInflater().inflate(R.layout.common_datetime, null);
		alertdialog = new AlertDialog.Builder(context).create();
		// alertdialog.set
		alertdialog.show();
		datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.datepicker);
		timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.timepicker);
		timePicker.setIs24HourView(true);
		if (!this.flag) {
			timePicker.setVisibility(View.GONE);
		}
		init(datePicker, timePicker);
		timePicker.setIs24HourView(true);
		timePicker.setOnTimeChangedListener(this);
		alertdialog.setContentView(dateTimeLayout);
		TextView title = (TextView) dateTimeLayout.findViewById(R.id.title);
		title.setText(titleString);
		Button check = (Button) dateTimeLayout.findViewById(R.id.sure);
		Button giveup = (Button) dateTimeLayout.findViewById(R.id.close);
		giveup.setText(giveupString);
		check.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				inputDate.setText(dateTime);

				if (callback != null) {
					if (needTomorrow) {
						if (timeRight) {
							callback.getChoseData(true, userChoseData);
						}
					} else {
						callback.getChoseData(true, userChoseData);
					}
				}
				alertdialog.dismiss();
			}
		});
		giveup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				inputDate.setText("点击选择时间");
				if (callback != null) {
					callback.getChoseData(false, null);
				}
				alertdialog.dismiss();
			}
		});
		// alertdialog.setTitle(initDateTime)
		// .setView(dateTimeLayout)
		// .setPositiveButton("确定", new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int whichButton) {
		// inputDate.setText(dateTime);
		// }
		// })
		// .setNegativeButton("取消", new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int whichButton) {
		// inputDate.setText("点击选择时间");
		// }
		// }).show();

		onDateChanged(null, 0, 0, 0);
		return alertdialog;

	}

	/**
	 * 
	 * @author 陈修园 回调接口
	 */
	public interface onChoseData {
		public void getChoseData(Boolean isChose, String dataString);
	}

	/**
	 * 
	 * @Title: setOnChoseData
	 * @Description: TODO(设置回调接口)
	 * @param @param callback 参数说明
	 * @return void 返回类型
	 * @throws
	 */
	public void setOnChoseData(onChoseData callback) {
		this.callback = callback;
	}

	/**
	 * 
	 * @Title: getCalendarByInintData
	 * @Description: TODO(初始化控件)
	 * @param @param initDateTime
	 * @param @return 参数说明
	 * @return Calendar 返回类型
	 * @throws
	 */
	private Calendar getCalendarByInintData(String initDateTime) {
		Calendar calendar = Calendar.getInstance();

		// 将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒
		String date = spliteString(initDateTime, "日", "index", "front"); // 日期
		String time = spliteString(initDateTime, "日", "index", "back"); // 时间

		String yearStr = spliteString(date, "年", "index", "front"); // 年份
		String monthAndDay = spliteString(date, "年", "index", "back"); // 月日

		String monthStr = spliteString(monthAndDay, "月", "index", "front"); // 月
		String dayStr = spliteString(monthAndDay, "月", "index", "back"); // 日

		String hourStr = spliteString(time, ":", "index", "front"); // 时
		String minuteStr = spliteString(time, ":", "index", "back"); // 分

		int currentYear = Integer.valueOf(yearStr.trim()).intValue();
		int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1;
		int currentDay = Integer.valueOf(dayStr.trim()).intValue();
		int currentHour = Integer.valueOf(hourStr.trim()).intValue();
		int currentMinute = Integer.valueOf(minuteStr.trim()).intValue();

		calendar.set(currentYear, currentMonth, currentDay, currentHour,
				currentMinute);
		return calendar;
	}

	/**
	 * 截取子串
	 * 
	 * @param srcStr
	 *            源串
	 * @param pattern
	 *            匹配模式
	 * @param indexOrLast
	 * @param frontOrBack
	 * @return
	 */
	public static String spliteString(String srcStr, String pattern,
			String indexOrLast, String frontOrBack) {
		String result = "";
		int loc = -1;
		if (indexOrLast.equalsIgnoreCase("index")) {
			loc = srcStr.indexOf(pattern); // 取得字符串第一次出现的位置
		} else {
			loc = srcStr.lastIndexOf(pattern); // 最后一个匹配串的位置
		}
		if (frontOrBack.equalsIgnoreCase("front")) {
			if (loc != -1)
				result = srcStr.substring(0, loc); // 截取子串
		} else {
			if (loc != -1)
				result = srcStr.substring(loc + 1, srcStr.length()); // 截取子串
		}
		return result;
	}

	@Override
	public void onTimeChanged(TimePicker arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		onDateChanged(null, 0, 0, 0);
	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		// TODO Auto-generated method stub
		// 获得日历实例
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat viewShowFormat;
		SimpleDateFormat serviceNeedFormat;
		if (flag) {

			calendar.set(datePicker.getYear(), datePicker.getMonth(),
					datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
					timePicker.getCurrentMinute(), 0);
			viewShowFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
			serviceNeedFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		} else {
			calendar.set(datePicker.getYear(), datePicker.getMonth(),
					datePicker.getDayOfMonth(), 0, 0, 0);
			viewShowFormat = new SimpleDateFormat("yyyy年MM月dd日");
			serviceNeedFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
		Calendar newtime = Calendar.getInstance();
		Calendar chose = calendar;
		newtime.set(Calendar.SECOND, 0);
		newtime.set(Calendar.MILLISECOND, 0);
		chose.set(Calendar.SECOND, 0);
		chose.set(Calendar.MILLISECOND, 0);
		// 当前时间是否是司机选择的时间之后
		if (needTomorrow) {
			if (!(newtime.after(chose))) {
				userChoseData = serviceNeedFormat.format(calendar.getTime());
				dateTime = viewShowFormat.format(calendar.getTime());
				alertdialog.setTitle(dateTime);
				timeRight = true;
			} else {
				timeRight = false;
				Toast.makeText(context, "注意日期不能是过去时间", Toast.LENGTH_LONG)
						.show();
			}
		}else {
			userChoseData = serviceNeedFormat.format(calendar.getTime());
			dateTime = viewShowFormat.format(calendar.getTime());
			alertdialog.setTitle(dateTime);
		}
	}

}
